<template>
	<view class="page">
		<cu-custom bgColor="bg-gradual-blue">
			<block slot="content">蓝牙连接</block>
		</cu-custom>

		<view class="padding-xl">
			<scroll-view class="ble_box" :scroll-y="true">
				<view class="services_list bg-white magin" @click="connBLE(device.deviceId)" v-for="(device,index) in  devices"
				 :key="index">
					<view class="name">
						设备名:{{device.name == '' ? '未知设备' : device.name}}
					</view>
					<view class="id">
						设备ID:{{device.deviceId}}
					</view>
					<view class="rssi">
						信号:{{device.RSSI}}
					</view>
				</view>
			</scroll-view>
			<button class="cu-btn block bg-black margin-tb-sm lg" :loading="discovering" @click="search()">{{discovering ? '搜索中':'搜索设备'}}</button>
		</view>

	</view>
</template>

<script>
	import toast from '@/common/toast/index.js'
	import {
		ab2str,
		setLight
	} from '@/common/msg-helper.js'
	import {
		BLE
	} from '@/config.js'
	export default {
		data() {
			return {
				bleUUID: {
					read: '',
					write: '',
					notify: ''
				},
				notifyValue: ''
			};
		},
		onLoad() {
			if (!this.isInit) {
				this.$store.dispatch('bluetooth/BLEInit')
			} else {
				this.$store.dispatch('bluetooth/getState')
			}
		},
		onShow() {
			this.$store.dispatch('bluetooth/findBLE')
		},
		computed: {
			deviceId() {
				return this.$store.state.bluetooth.deviceId
			},
			discovering() {
				return this.$store.state.bluetooth.discovering
			},
			devices() {
				return this.$store.state.bluetooth.devices
			},
			isInit() {
				return this.$store.state.bluetooth.isInit
			},
			isConn() {
				return this.$store.state.bluetooth.isConn
			}
		},
		methods: {
			search() {
				if (this.discovering) {
					this.$store.dispatch('bluetooth/stopFind')
				} else {
					this.$store.dispatch('bluetooth/findBLE')
				}
			},
			connBLE(deviceId) {
				if (deviceId == this.deviceId) {
					toast.message('已连接当前蓝牙')
					this.$store.dispatch('bluetooth/stopFind')
					return
				}
				uni.showLoading({
					title: '连接中...',
				})
				this.$store.dispatch('bluetooth/closeConn').then(() => {
					this.$store.dispatch('bluetooth/connBLE', deviceId).then((res) => {
						this.$store.dispatch('bluetooth/stopFind')
						this.$store.dispatch('bluetooth/listenBLE')
						uni.hideLoading()
					}).catch(() => {
						uni.hideLoading()
						toast.error('连接失败')
					})
				})
			}
		}
	}
</script>

<style lang="scss">
	.page {
		background-color: #fff;
		height: 100vh;

		.ble_box {
			height: 70vh;
			border: 1px #eee solid;

			.services_list {
				margin: 10rpx;
				border-bottom: 1px #eee solid;

				.name {
					font-size: 32rpx;
					color: #000;
					padding: 10rpx;
					padding-left: 30rpx;
				}

				.id,
				.rssi {
					padding: 10rpx;
					padding-left: 30rpx;
				}
			}
		}
	}
</style>
